<template>
    <div :class="[flag ? 'version-tree-a-flag' : '']" ref="versionTreeARef">
        <!-- 无子产品或者有子产品，不统一发版的  -->
        <HCollapse v-model:expanded="expanded" collapse @change="handleLoadData">
            <template #title>
                <flexbox style="color: #70798b">
                    <span class="font-w-b">{{ detail.versionNumber }} </span>
                    <span class="margin-l-8 font-w-b" v-if="signPostShowType === '3'">{{ detail.pmpProductDetailDTO.systemName }}</span>
                    <flexbox style="flex: 1; white-space: nowrap; overflow: hidden" justify="center">
                        <span>{{ detail.startTime }}~{{ detail.onlineTime }}</span>
                    </flexbox>
                </flexbox>
            </template>
            <!-- 无子产品的或者有子产品，不统一发版的 -->
            <div style="padding-left: 4px" v-if="subVersionSystemList.length">
                <CommonTaskRequireList
                    :list="subVersionSystemList[0].pmpRequestInfos"
                    :disabled="disabled"
                    :versionDetail="subVersionSystemList[0]"
                    @success="handleLoadData"
                />
                <CommonProRequireList
                    :list="subVersionSystemList[0].pmpProductRequires"
                    :disabled="disabled"
                    :versionDetail="subVersionSystemList[0]"
                    @success="handleLoadData"
                />
            </div>
            <template #titleExtra>
                <flexbox justify="flex-end" align="center" style="width: 100%; color: #333b4b" v-if="!disabled">
                    <flexbox @click.stop="handleEdit">
                        <my-icon type="iconbianji" />
                        <span style="margin-left: 4px">编辑</span>
                    </flexbox>
                    <flexbox class="margin-l-16" @click.stop="handleDelete">
                        <my-icon type="icondelete" />
                        <span style="margin-left: 4px">删除</span>
                    </flexbox>
                </flexbox>
            </template>
        </HCollapse>
        <CreateVersionModal ref="CreateVersionModalRef" :lubiaoDetail="lubiaoDetail" :subVersionInfo="subVersionInfo" @success="handleSuccess" />
    </div>
</template>

<script lang="ts">
import store from '@/store';
import { useDrop } from '@/hooks/content/useDrop';
import CreateVersionModal from '../../VersionModal/CreateVersionModal.vue';
import CommonProRequireList from '../components/CommonProRequireList.vue';
import CommonTaskRequireList from '../components/CommonTaskRequireList.vue';
import api from '@/api';
import { message } from 'ant-design-vue';
import { useMessage } from '@/hooks/common/useMessage';
import HCollapse from '../components/HCollapse.vue';
import { defineComponent, reactive, toRefs, ref, unref, getCurrentInstance, onMounted } from 'vue';
export default defineComponent({
    components: {
        HCollapse,
        CreateVersionModal,
        CommonProRequireList,
        CommonTaskRequireList
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        },
        lubiaoDetail: {
            type: Object,
            default: () => ({})
        },
        signPostShowType: {
            type: String,
            default: ''
        },
        subVersionInfo: {
            type: Object,
            default: () => ({})
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const instance: any = getCurrentInstance();
        const versionTreeARef = ref<any>({});
        const CreateVersionModalRef = ref<any>();
        const state = reactive<any>({
            subVersionSystemList: [],
            lastenter: null,
            flag: false,
            expanded: false
        });
        const handleLoadData = async (expanded) => {
            if (expanded) {
                const query = {
                    versionNumber: props.detail.versionNumber,
                    catalogCode: props.detail.catalogCode
                };
                const { success, moule } = await api.versionModel.findByVerNoAndCatalogCode(query);
                if (success) {
                    state.subVersionSystemList = [...moule];
                }
            }
        };
        const handleEdit = () => {
            unref(CreateVersionModalRef).open(props.detail);
        };
        const handleDelete = () => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: `确认删除【${props.detail.versionNumber}】？`,
                iconType: 'danger',
                onOk: async () => {
                    const query = {
                        id: props.detail.id
                    };
                    const { success, errorMsg } = await api.versionControlModel.delete(query);
                    if (success) {
                        if (props.detail.versionIds) {
                            const { success, errorMsg } = await api.versionModel.deleteById({
                                id: props.detail.versionIds
                            });
                            if (success) {
                                handleSuccess();
                                message.success('删除成功');
                            } else {
                                message.error(errorMsg);
                            }
                        } else {
                            handleSuccess();
                            message.success('删除成功');
                        }
                    } else {
                        message.error(errorMsg);
                    }
                }
            });
        };
        const handleSuccess = () => {
            emit('success');
        };
        // 更新展开接口
        instance.proxy.$mitt.on('taskRequireList-subVersionSystemList-loadData', () => {
            handleLoadData(true);
        });

        const handleShow = (ev: Event) => {
            ev.preventDefault();
            state.lastenter = ev.target;
            state.expanded = true;
            handleLoadData(true);
            state.flag = true;
        };
        const handleHide = (ev: Event) => {
            if (state.lastenter === ev.target) {
                state.flag = false;
                ev.stopPropagation();
                ev.preventDefault();
            }
        };
        // 绑定业务需求
        const handleUpdateTaskBatch = async (item) => {
            if (!state.subVersionSystemList.length) {
                message.error('该版本下无法移入');
                return;
            }
            const query = {
                businessId: item.id,
                versionId: state.subVersionSystemList[0].id,
                type: 'add'
            };
            const { success, errorMsg } = await api.pmpRequestInfoModel.signpostBVSave(query);
            if (success) {
                const { type } = store.getters.moveData;
                if (type === 1) {
                    // 刷新业务需求列表
                    instance.proxy.$mitt.emit('taskRequireList-subversionSystemItem-refreshTaskList', {}, true);
                } else {
                    // 刷新业务需求列表
                    instance.proxy.$mitt.emit('unVersionTaskRequireList-subversionSystemItem-refreshTaskList', {}, true);
                }
                handleLoadData(true);
            } else {
                message.error(errorMsg);
            }
        };
        // 绑定产品需求
        const handleUpdateProBatch = async (item) => {
            const { empId, name } = store.getters.userInfo.employeeDTO;
            const query = [
                {
                    productRequireId: item.id,
                    relateVersionId: state.subVersionSystemList[0].id,
                    relateVersionName: state.subVersionSystemList[0].versionName,
                    relateVersionNumber: state.subVersionSystemList[0].versionNumber,
                    status: 'add',
                    empId,
                    empName: name
                }
            ];
            const { success, errorMsg } = await api.productRequireModel.batchDeal(query);
            if (success) {
                handleLoadData(true);
                // 刷新产品需求列表
                instance.proxy.$mitt.emit('unVersionProRequireList-subversionSystemItem-refreshProList', {}, true);
            } else {
                message.error(errorMsg);
            }
        };

        const onDrop = () => {
            state.flag = false;
            const { type } = store.getters.moveData;
            switch (type) {
                case 1:
                case 2:
                    handleUpdateTaskBatch(store.getters.moveData);
                    break;
                case 3:
                    handleUpdateProBatch(store.getters.moveData);
                    break;
            }
        };

        onMounted(() => {
            useDrop(unref(versionTreeARef), {
                onShow: handleShow,
                onHide: handleHide,
                onDrop
            });
        });

        return {
            CreateVersionModalRef,
            versionTreeARef,
            ...toRefs(state),
            handleLoadData,
            handleEdit,
            handleDelete,
            handleSuccess
        };
    }
});
</script>
<style lang="less" scoped>
::v-deep(.ant-collapse-content > .ant-collapse-content-box) {
    padding-bottom: 2px !important;
}
.version-tree-a-flag {
    border: 1px dashed @primary-color;
}
</style>